package Lab2ContainerAndIO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Lab2 {
	// 用Reader读取内容
	public static String txtReader(String filename) throws Exception {
		Reader reader = null;
		StringBuffer buf = new StringBuffer();
		try {
			reader = new FileReader(filename);
			char[] chars = new char[1024];
			int len = -1;
			while((len = reader.read(chars)) != -1) {
				String str = new String(chars, 0, len);
				buf.append(str);
			} 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return buf.toString();
	}
	
	// 用InputStream读取内容
	public static String txtInputStream(String filename) throws Exception {
		InputStream inStream = null;
		StringBuffer buf = new StringBuffer();
		try {
			inStream = new FileInputStream(filename);
			byte[] b = new byte[1024*10];
			int len = -1;
			while((len = inStream.read(b)) != -1) {
				String str = new String(b, 0, len);
				buf.append(str);
			} 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return buf.toString();
	}
	
	// 将文本文件按照空格拆分
	public String[] splitContent(String content) {
		String contents[] = content.split("\\s+");
		String[] a = new String[contents.length-1];
		for(int i = 0; i < contents.length-1; i++) {
			a[i] = contents[i+1];
		}
		return a;
	}

	// 计算频率
	public Map<String, Integer> getStringFrequent(String[] words) throws Exception {
		Map<String, Integer> map = new HashMap<>();
		Set<String> word = map.keySet();
		for(int i = 0; i < words.length; i++) {
			if( !word.contains(words[i] )) {
				map.put(words[i], 1);
			}
			else {
				Integer count = map.get(words[i]);
				count++;
				map.put(words[i], count);
			}
		}
		return map;
	}
	
	// 降序排列
	public List<Map.Entry<String, Integer>> invert(Map<String, Integer> map){
		List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>(){
			
			@Override
			public int compare(Entry<String, Integer> arg0, Entry<String, Integer> arg1) {
				// TODO Auto-generated method stub
				return -arg0.getValue().compareTo(arg1.getValue());
			}
		});
		return list;
	}
}
